@extends('layouts.base')

@section('header_css')
    <script src="/assets/d2eace91/js/jquery.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/jquery.cookie.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/layer/layer.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/jquery.method.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/jquery.modal.js?v=20190121"></script>
    <script src="/frontend/js/common.js?v=20190121"></script>
    <!-- 图片缓载js -->
    <script src="/assets/d2eace91/js/jquery.lazyload.js?v=20190121"></script>
    <script src="/frontend/js/topic.js?v=20190121"></script>
    <script src="/frontend/js/tabs.js?v=20190121"></script>
    <script src="/frontend/js/index_tab.js?v=20190121"></script>
    <!-- ****** 表单内容 ****** -->
    <link rel="stylesheet" href="/assets/d2eace91/fonts/css/font-awesome.min.css?v=20190215"/>
    <link rel="stylesheet" href="/assets/d2eace91/css/common.css?v=20190215"/>
    <link rel="stylesheet" href="/assets/d2eace91/css/customform/design.css?v=20190215"/>
    <script src="/assets/d2eace91/js/jquery-1.9.1.min.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/jquery.superslide.2.1.1.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/layer/layer.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/jquery.method.js?v=20190121"></script>
    <link rel="stylesheet" href="/assets/d2eace91/css/customform/edit.css?v=20190215"/>
    <!-- ****** 表单内容 ****** -->
    <script type="text/javascript">
        $().ready(function() {
        })
    </script>
@stop

{{--follow_box 注意此效果只在首页面展示--}}
@section('follow_box')

@stop

@section('style_js')
    <!--页面css/js-->
    <script src="/frontend/js/index.js?v=20190121"></script>
    <script src="/frontend/js/tabs.js?v=20190121"></script>
    <script src="/frontend/js/bubbleup.js?v=20190121"></script>
    <script src="/frontend/js/jquery.hiSlider.js?v=20190121"></script>
    <script src="/frontend/js/index_tab.js?v=20190121"></script>
    <script src="/frontend/js/jump.js?v=20190121"></script>
    <script src="/frontend/js/nav.js?v=20190121"></script>
@stop



@section('content')


    <!-- 内容 -->
    <!--页面头部-->
    <div class="p-t-20 F-main">

        <!--此处为表单设置背景颜色-->
        <!--浏览页是将表单内容中所有编辑按钮和drop-field样式都去掉-->
        <div class="center-form center-main ">

            <div class="top-images">
                <img src="{{ $form_info['global_data']['page_header']['header'] }}" style="width: 100%;">
            </div>

            <div class="center-content ">
                <!--不可删不可移可编辑-->

                <div class="form-title">{{ $form_info['global_data']['page_title']['title'] }}</div>


                <div class="form-desc">{!! $form_info['global_data']['page_desc']['description'] !!}</div>

                <form id="add_form">
                    <!--可删可移可编辑-->
                    <ul id="dropzone" class="ui-sortable">

                        @foreach($form_info['form_data'] as $k=>$form)
                            <li id="c{{ $k }}">
                                <div class="type-content">

                                    {{--根据type switch 判断展示不同的元素--}}
                                    {{--引入万能表单元素--}}
                                    @include('frontend::components.custom-form.form_items')

                                </div>
                            </li>
                        @endforeach

                    </ul>

                    {{ csrf_field() }}

                </form>
                <!--提交按钮不可删不可移可编辑-->
                <div class="form-submit">
                    <a href="javascript:;">提交</a>
                </div>
            </div>
        </div>
        <a class="FshareBtn" title="通过二维码分享此表单"></a>
        <div class="clear"></div>
    </div>
    <div class="form-end" style="display: none;">
        <!--提交成功-->
        <img src="/assets/d2eace91/images/customform/success.png" alt="提交成功" class="end-img">
        <h2 class="end-title">提交成功！</h2>
        <p class="end-desc">我们已收到您的反馈，感谢填写。</p>
        <a href="/shop/{{ $form_info['shop_id'] }}.html" class="btn">返回首页</a>
    </div>
    <!--点击分享-->
    <div class="shareMask">
        <div class="popInnerAnimation">
            <img class="scannerQRCode" src="/customform/form/form-qrcode.html?form_id={{ $form_info['form_id'] }}">
            <div class="scannerGuide">
                <p>扫描二维码，分享给好友</p>
            </div>
        </div>
    </div>
    <script src="//webapi.amap.com/maps?v=1.4.9&key={{ sysconf('amap_js_key') }}"></script>
    <!-- 日期选择器 -->
    <script src="/assets/d2eace91/bootstrap/datetimepicker/js/bootstrap-datetimepicker.js?v=20190121"></script>
    <script src="/assets/d2eace91/bootstrap/datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js?v=20190121"></script>
    <!-- 地址 -->
    <script src="/assets/d2eace91/js/jquery.region.js?v=20190121"></script>
    <!-- 表单验证 -->
    <script src="/assets/d2eace91/js/validate/jquery.validate.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/validate/jquery.validate.custom.js?v=20190121"></script>
    <script src="/assets/d2eace91/js/validate/messages_zh.js?v=20190121"></script>
    <script>
        var form_id = {{ $form_info['form_id'] }};
        // 存储的表单数据
        var form_datas = {!! json_encode($form_info['form_data']) !!};
        var global_datas = {!! json_encode($form_info['global_data']) !!};
        var data = {
            form_datas: JSON.stringify(form_datas),
            global_datas: JSON.stringify(global_datas)
        };

        // 日期级别
        var time_level = {
            // 年月日
            "0": {
                startView: 2,
                minView: 2,
                maxView: 4,
                format: "yyyy-mm-dd"
            },
            // 年月日时分秒
            "1": {
                startView: 2,
                minView: 0,
                maxView: 4,
                format: "yyyy-mm-dd hh:ii:ss"
            }
        };

        // 下拉地址setting
        var selector_setting = {
            value: '',
            sale_scope: 0,
            widget_class: 'render-selector',
            select_class: "m-r-5",
            // 在将组件添加到页面之后就会被调用
            // element是当前select的对象
            select_callback: function(element) {
                var o_region_container = this.container;
                // var o_region_container = element.closest('.region_container');
                // 检测当前select数量的个数, 因为可能会有更多级, 只保留3级联动
                var len = o_region_container.find('.render-selector').length;
                if (len > 2) {
                    o_region_container.find('.render-selector:gt(2)').remove();
                }
            },
            change: function(element, text) {
                var o_region_container = this.container;
                // element是code值，如11,01,02
                var elements = element.split(',');
                // 获取隐藏域对象
                var o_address = o_region_container.nextAll('.full_address:eq(0)');
                if (elements.length == 3) {
                    // 所有的文本内容 传递code不传text
                    // var address_text = text.join('');
                    var address_text = element;
                    // 获取详细地址内容
                    var detail = $.trim(o_region_container.next('.form-group').find('.address_detail').val());
                    if (detail != '') {
                        address_text += ' ' + detail;
                        o_address.val(address_text);
                    } else {
                        o_address.val('');
                    }

                } else {
                    o_address.val('');
                }
            }
        }

        // 级联地址的详细地址改变监听
        var o_address_detail = $('.address_detail');
        o_address_detail.blur(function() {
            var self = $(this);
            var detail = $.trim(self.val());
            if (detail != '') {
                var o_region_container = self.parent().prev('.region_container');
                var o_full_address = self.parent().next('.full_address');
                if (o_region_container.length == 1 && o_full_address.length == 1) {
                    var o_region_selector = o_region_container.find('.render-selector');
                    if (o_region_selector.length == 3) {
                        var address = [];
                        o_region_selector.each(function(i, v) {
                            var self = $(this);
                            var code = self.val();
                            // var text = self.find('option:selected').text();
                            if (code != "") {
                                address.push(code);
                            }
                        });
                        if (address.length == 3) {
                            // var address_text = address.join('');
                            var address_text = address[2];
                            o_full_address.val(address_text + ' ' + detail);
                        }
                    }
                }
            } else {
                // 没有填写详细地址则清空内容
                self.closest('.question-conent').find('.full_address').val('');
            }
        });

        var validates = {
            rules: {},
            messages: {}
        };

        // 整数
        var pattern_int = /^\d+$/;
        // 身份证
        var pattern_cardnum = /(^\d{15}$)|(^\d{17}(\d|[X|x])$)/;
        // 手机号
        var pattern_phone = /((^(13|15|18|17|14)\d{9}$)|(^(199|198|166)\d{8}$))/;

        // 整数
        function isInt(val) {
            return pattern_int.test(val)
        }
        // 身份证
        function isCardNum(val) {
            return pattern_cardnum.test(val);
        }
        // 手机号
        function isPhoneNum(val) {
            return pattern_phone.test(val);
        }
        /**
         * 根据type，获取对应的校验内容
         * @paran object data 组件的设置的内容
         */
        function typeOfValidate(type, data, index) {
            // 组件类型
            var component_type = data.type;
            // 组件名称
            var component_name = getComponentName(index, data);
            // 校验的规则
            var validate = {};
            // 规则集合
            var rules = {};
            // 提示信息集合
            var messages = {};
            // 数字默认要输入数字
            if (component_type === 'number') {
                rules.number = true;
            }
            // 邮箱基本校验规则
            if (component_type === 'email') {
                rules.email = true;
            }
            // qq号就只有整数
            if (component_type === 'qq' || component_type === 'phone') {
                rules.digits = true;
                if (component_type === 'phone') {
                    rules.isPhoneNum = true;
                }
            }

            // 是否必填
            var v_required = data.v_required;
            if (v_required && v_required == 1) {
                rules.required = true;
            }

            // 最少多少字
            var v_minlength = data.v_minlength;
            var v_minlength_con = data.v_minlength_con;
            // 最多多少字
            var v_maxlength = data.v_maxlength;
            var v_maxlength_con = data.v_maxlength_con;
            // 最多最少填写多少字，且必须是数字
            if (v_minlength && v_minlength == 1 && v_minlength_con && isInt(v_minlength_con)) {
                rules.minlength = parseInt(v_minlength_con);
            }
            if (v_maxlength && v_maxlength == 1 && v_maxlength_con && isInt(v_maxlength_con)) {
                rules.maxlength = parseInt(v_maxlength_con);
            }
            // 但是最多必须要大于最少
            if (v_minlength == 1 && isInt(v_minlength_con) && v_maxlength == 1 && isInt(v_maxlength) && parseInt(v_minlength_con) > parseInt(v_maxlength_con)) {
                // 如果最小 > 最大 不合法数字，则去除此校验
                delete rules.maxlength;
                delete rules.minlength;
            }
            // 身份证验证
            var v_resident_cardnum = data.v_resident_cardnum;
            if (v_resident_cardnum && v_resident_cardnum == 1) {
                rules.isCardNum = true;
            }

            // 自定义出错内容
            var v_error_customer = data.v_error_customer;
            var v_error_customer_con = data.v_error_customer_con;
            if (v_error_customer && v_error_customer == 1 && v_error_customer_con != '') {
                if (v_required) {
                    messages.required = v_error_customer_con;
                }
            }

            validate['rules'] = rules;
            validate['messages'] = messages;
            return validate;

        }

        // 身份证验证
        jQuery.validator.addMethod("isCardNum", function(value, element, param) {
            // 必须有值才验证
            value = $.trim(value);
            if (value != '')
            {
                return isCardNum(value);
            }
            return true;
        }, $.validator.format("请输入正确身份证号码"));
        // 手机号码验证
        jQuery.validator.addMethod("isPhoneNum", function(value, element, param) {
            value = $.trim(value);
            if (value != '')
            {
                return isPhoneNum(value);
            }
            return true;
        }, $.validator.format("请输入正确手机号"));

        // 遍历日期组件
        if (form_datas) {
            var form_datas_len = form_datas.length;
            for (var i = 0; i < form_datas_len; i++) {
                // 获取当前组件的数据内容
                var component = form_datas[i];
                // 获取当前组件的类型
                var type = component.type;
                // 初始化组件对应的数据
                initPreviewComponents(i, type, component);
                // 生成校验规则
                var validate = typeOfValidate(type, component, i);

                var component_name = getComponentName(i, component);
                var rules = validate.rules;
                var messages = validate.messages;

                validates['rules'][component_name] = rules;
                validates['messages'][component_name] = messages;
            }
        }

        // 表单
        var o_add_form = $('#add_form');
        // 提交事件
        var prevent = {
            errorPlacement: function(error, element) {
                // 需要将提示信息放在总内容的后面
                var target_element = $(element).closest('.question-conent');

                var error_id = $(error).attr("id");
                var error_msg = $(error).text();
                var element_id = $(error).attr("for");

                if ($.trim(error_msg).length == 0) {
                    $(error).remove();
                    return;
                }

                var error_html = $("<span id=\"" + error_id + "\" data-error-id=\"" + error_id + "\" class=\"form-control-error\"><i class=\"fa fa-warning\"></i>" + error_msg + "</span>");

                $(error_html).click(function() {
                    $(element).focus();
                });

                var control_box = $(element).parents(".form-control-box");
                if ($(control_box).size() > 0) {
                    if ($(control_box).first().parent().find(".form-control-error").size() > 0) {

                        $(control_box).first().parent().find(".form-control-error").replaceWith(error_html);
                    } else {
                        $(control_box).first().after(error_html);
                    }
                    return;
                }

                // 防止ID为jquery里的规则查不出来表单元素对象
                var error_dom = null;
                if ($(element).parents("form").size() > 0) {
                    error_dom = $(element).parents("form").find("[id='" + error_id + "']");
                } else {
                    error_dom = document.getElementById("[id='" + error_id + "']");
                }
                if ($(error_dom).size() > 0) {
                    if ($(error_dom).text() == error_msg) {
                        return;
                    }
                    $(error_dom).remove();
                }

                if ($(element).is(":file")) {
                    $(element).parent().parent().after(error_html).attr("style", "float: left;");
                } else if ($(element).prop("tagName") == "SELECT" && $(element).hasClass("chosen-select")) {
                    if ($(element).data('chosen') && $(element).data('chosen').container) {
                        $($(element).data('chosen').container).css("float", "left");
                    }
                    target_element.after(error_html);
                } else {
                    target_element.after(error_html);
                }

            },
        }
        // 合并内容
        $.extend(validates, prevent);
        // 数据校验
        var validator = o_add_form.validate(validates);
        $('.form-submit').find('a').click(function() {
            if (!validator.form())
            {
                return;
            }
            $.loading.start();
            var data = $('#add_form').serialize();
            $.post('/customform/form/add.html?id=' + form_id, data, function(res) {
                if (res.code == -1) {
                    $.msg(res.message);
                } else {
                    // 提交成功
                    $.open({
                        type: 1,
                        title: false,
                        closeBtn: 0,
                        area: ['80%'],
                        content: $('.form-end')
                    });
                }
            }, 'JSON').always(function() {
                $.loading.stop();
            });
            return false;
        });

        /**
         * 初始化地图内容
         * @param int index 组件的位置索引
         * @param string type 组件的类型
         */
        function initPreviewComponents(index, type, component) {
            switch (type) {
                // 时间
                case "time":
                    // ----- 默认时间插件 ----- //
                    var default_time_setting = {
                        language: 'zh-CN',
                        weekStart: 1,
                        todayBtn: 1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 2,
                        forceParse: 1,
                        showMeridian: 1,
                        minView: 2,
                        maxView: 4,
                        format: "yyyy-mm-dd"
                    };
                    // 获取当前组件对象
                    var obj = getComponentObj(index);
                    // 获取当前时间级别
                    var level = component.time_level;
                    $.extend(default_time_setting, time_level[level]);
                    obj.find('.datetimepicker').datetimepicker(default_time_setting);
                    break;
                // 地图
                case "static_map":
                    // 获取地图的经纬度
                    var lat = component.location.lat;
                    var lng = component.location.lng;
                    var marker_text = component.place;
                    // 获取地图的缩放 zoom
                    var zoom = component.zoom;
                    zoom = parseInt(zoom);

                    // 初始化地图数据
                    var map = new AMap.Map('map_container_' + index, {
                        viewMode: '2D',
                        zoom: zoom,
                        scrollWheel: false,
                        resizeEnable: true,
                        dragEnable: false,
                        center: [lng, lat], // 地图中心点
                    });
                    // 初始化点标注
                    var marker = new AMap.Marker({
                        position: [lng, lat],
                        // 小图标的高度是 19 * 33
                        offset: new AMap.Pixel(-10, -33),
                    });
                    // 标注打开内容
                    marker.on('click', function() {
                        openMapWindowInfo(marker_text, map, this);
                    });
                    // 将点添加到地图上
                    map.add(marker);
                    // 打开窗体信息
                    openMapWindowInfo(marker_text, map, marker);
                    break;
                case 'address':
                    // ----- 地区级联插件 ----- //
                    var obj = getComponentObj(index);
                    var o_region_container = obj.find('.region_container');

                    if (selector_setting) {
                        selector_setting.value = component.address.address_code;
                        o_region_container.regionselector(selector_setting);
                    }
                    break;
            }
        }

        /**
         * 获取索引获取当前ID
         * @param int index 当前组件的索引顺序
         */
        function getComponentID(index) {
            return 'c' + index;
        }
        /**
         * 获取组件对象
         * @param int index 当前组件的索引顺序
         */
        function getComponentObj(index) {
            var id = getComponentID(index);
            return $('#' + id);
        }

        /**
         * 获取组件的name 规则是 组件类型_组件索引
         * @param int index 组件所在索引
         * @param object data 组件的数据
         */
        function getComponentName(index, data) {
            var type = data.type;
            var muti = '';
            if (type === 'checkbox') {
                muti = '[]';
            }
            return type + '_' + index + muti;
        }
        //分享二维码
        $(".FshareBtn").click(function() {
            $(".shareMask").addClass("show");
            $(".F-main").addClass("form-disabled");
        });
        $(".shareMask").click(function() {
            $(".shareMask").removeClass("show");
            $(".F-main").removeClass("form-disabled");
        });
        /**
         * 打开信息窗体
         */
        function openMapWindowInfo(text, map, marker) {
            if (text != "")
            {
                // 构建信息窗体中显示的内容
                var info = [];
                info.push("<div style='font-size:12px;'>" + text + "</div>");
                infoWindow = new AMap.InfoWindow({
                    offset: new AMap.Pixel(2, -25),
                    content: info.join("<br/>")  // 使用默认信息窗体框样式，显示信息内容
                });
                infoWindow.open(map, marker.getPosition());
            }
        }
    </script>

@stop